import socket
import threading

def handle_client_socket(client_socket,addr_tuple):
    # 5.等待客户端连接 返回客户端套接字和地址元祖
    print("地址元组：", addr_tuple)
    print("客户端套接字：", client_socket)
    while True:
        # 6.接收客户端数据
        data = client_socket.recv(1024)
        if data:
            str = data.decode('gbk')
            print("接受客户端数据：", str)
            # 7.发送数据到客户端
            client_socket.send("你好呀".encode('gbk'))
        else:
            print(addr_tuple,"已经断开连接了！")
            break
    # 8.释放客户端套接字
    client_socket.close()


if __name__ == '__main__':
    # 1.创建服务端套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 2.设置端口服用
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 3.绑定端口
    server_socket.bind(("", 8989))
    # 4.设置监听
    server_socket.listen(128)
    while True:
        (client_socket, addr_tuple) = server_socket.accept()
        sub_thread = threading.Thread(target=handle_client_socket,args=((client_socket,addr_tuple)))
        sub_thread.daemon = True
        sub_thread.start()
    server_socket.close()